#!/usr/bin/env python
# Create: 2018/8/10
__author__ = '749B'
from django.shortcuts import render


class ModelAdmin(object):
    list_display = ()
    list_filter = ()
    search_fields = ()
    list_editable = ()
    readonly_fields = ()
    filter_horizontal = ()
    default_actions = ('delete_selected',)
    actions = ()
    list_per_page = 20

    def __init__(self, model):
        self.model = model
        self.actions = self.default_actions + self.actions
        # 给actions里所有没设置short_description的函数，添加该属性，默认就是函数名
        for func_name in self.actions:
            func = getattr(self, func_name)
            if not hasattr(func, 'short_description'):
                func.__func__.short_description = func.__name__

    def delete_selected(self, request, queryset):
        app_label = request.resolver_match.kwargs['app_label']
        model_name = request.resolver_match.kwargs['model_name']
        admin_obj = site.registered_sites[app_label]['registers'][model_name]
        return render(request, 'steed_admin/table_del_confirm.html', {'admin_obj': admin_obj, 'objs': queryset})
    delete_selected.short_description = "删除选择的记录"


class AdminSite(object):

    def __init__(self):
        self.registered_sites = {}

    def register(self, model, admin_class=None):
        if admin_class is None:
            admin_class = ModelAdmin
        meta = model._meta
        app_label = meta.app_label
        model_name = meta.model_name
        if app_label not in self.registered_sites:
            self.registered_sites[app_label] = {'app_config': meta.app_config, 'registers': {}}
        # 每个注册的model，都要有一个admin_class()对象
        # 如果不实例化，所有admin_class=None进来的注册，用的都是同一快内存空间
        # 用了自定义的admin_class的,是否实例化都是独立的内存空间，不过就统一做一个实例化，大家保存的都是对象
        admin_obj = admin_class(model)
        # 下面这些实例化之后要存入的内容，都应该写到基类的构造函数里
        # 实例化之后，把默认的动作统一加到每一个实例里动作元祖的开头。元祖不能改变，实际是组合后生成一个新的元祖
        # admin_obj.actions = ModelAdmin.default_actions + admin_obj.actions
        # admin_obj.model = model
        self.registered_sites[app_label]['registers'][model_name] = admin_obj


"""
registered_sites = {
    'crm': {
        'app_config': app_config,
        'registers': {
            'model_name': admin_obj,
            'model_name2': admin_obj2,
            'model_name3': admin_obj3,
        }
    }
}
"""

site = AdminSite()


